#coding=utf-8
#LightCam 私有库
#init by hfh 20150212

import sys,logging,logging.handlers,time,hashlib
import subprocess,traceback
import sqlite3,pymongo

#获取LCHOME
def lc_getlchome():
	cmd='echo $LIGHTCAM_HOME'
	popen=subprocess.Popen(cmd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
	lchome=popen.stdout.read().strip('\r\n')
	return lchome

#获取主机名称
def lc_gethostname():
	comd='hostname'
	popen=subprocess.Popen(comd,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
	line=popen.stdout.read().strip("\n").strip("\r")
	line=line.lower()
	return line

#返回时间(秒)
def lc_returnseconds(timestring):
	ts=timestring.split()
	#ts[0]=seconds,ts[1]=minutes,ts[2]=hours,ts[3]=days,ts[4]=months,ts[5]=years
	seconds=int(ts[0])+int(ts[1])*60+int(ts[2])*60*60+int(ts[3])*24*60*60+int(ts[4])*30*24*60*60+int(ts[5])*365*30*24*60*60
	return seconds

#生成告警信息
def lc_gen_alert(agent_hostname,Node,AlertGroup,AlertKey,Severity,Type,Summary):
	res="Manager:"+str(agent_hostname)+" Agent:LightCam Node:"+str(Node)+" AlertGroup:"+str(AlertGroup)+" AlertKey:"+str(AlertKey)+" Severity:"+str(Severity)+" Type:"+str(Type)+" Summary:"+str(Summary)
	return res

	
#发送告警事件
def lc_alert(AlertMessage):
	try:
		agent_hostname=lc_gethostname()
		lchome=lc_getlchome()
		logfile=file(lchome+'/log/lc_alert.log','a')

		ServerIP="127.0.0.1"
		ServerPort=514
		
		rootLogger = logging.getLogger('')
		rootLogger.setLevel(logging.WARNING)
		
		for line in open(lchome+"/conf/lc_alert.conf"):
			if line[0] == '#':
				continue
			else:
				lines=line.strip('\n').split("\t")
				if len(lines)<3 or lines[0] not in (agent_hostname,'default'):
					continue
				else:
					ServerIP=lines[1]
					ServerPort=int(lines[2])
					
					socketHandler = logging.handlers.SysLogHandler((ServerIP,ServerPort))
					rootLogger.addHandler(socketHandler)
					
					logging.warning(AlertMessage)
					
					rootLogger.removeHandler(socketHandler)
					socketHandler.close()
					
					logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
					logfile.write(logdate+" "+ServerIP+" "+str(ServerPort)+" "+AlertMessage+"\n")
		
	except Exception:
		excinfo=traceback.format_exc()
		logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		logfile.write(logdate+" :\n"+excinfo+"\n")
		logfile.flush()
	logfile.close()
	
#返回比较值
def lc_operator(input1,oper,input2):
	if oper == 'e' or oper == 'eq':
		return input1 == input2
	if oper == 'ne':
		return input1 <> input2
	elif oper == 'l' or oper == 'lt':
		return input1 < input2
	elif oper == 'g' or oper == 'gt':
		return input1 > input2
	elif oper == 'le':
		return input1 <= input2
	elif oper == 'ge':
		return input1 >= input2
	elif oper == 'in':
		return input1 in input2
	elif oper == 'rn':
		return input2 in input1
		
#返回是否在时间策略内
def lc_schedule(schedules):

	Flag=False
	for schedule in schedules.split('|'):
		beginweekday=int(schedule.split(',')[0].split('-')[0])
		endweekday=int(schedule.split(',')[0].split('-')[1])
		beginhour=int(schedule.split(',')[1].split('-')[0].split(':')[0])
		beginminute=int(schedule.split(',')[1].split('-')[0].split(':')[1])
		endhour=int(schedule.split(',')[1].split('-')[1].split(':')[0])
		endminute=int(schedule.split(',')[1].split('-')[1].split(':')[1])
		
		current_weekday=time.localtime()[6]
		current_hour=time.localtime()[3]
		current_minute=time.localtime()[4]
		
		current_time=current_hour*60+current_minute
		begintime=beginhour*60+beginminute
		endtime=endhour*60+endminute
		
		if current_weekday < beginweekday or current_weekday > endweekday:
			pass
		elif current_time < begintime or current_time >= endtime:
			pass
		else:
			Flag=True
	return Flag
	
#返回是否在holidays中
def lc_isholiday():
	today=time.strftime('%Y-%m-%d',time.localtime())
	lchome=lc_getlchome()
	file=open(lchome+'/conf/lc_holiday.conf','r')
	holiday=file.read()
	file.close()
	if today in holiday:
		return True
	else:
		return False

#发送告警事件,写日志,重置标志文件为告警状态
def lc_sendalert(alertfilename,strs,logfile):
	#init
	alertfile=open(alertfilename,'a')
	alertfile.write("")
	alertfile.flush()
	alertfile.close()
	#read flag
	alertfile=open(alertfilename,'r')
	flag=alertfile.read()
	if "0" in flag or "1" not in flag:
		lc_alert(strs)
		logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		logfile.write(logdate+" "+strs+"\n")
		logfile.flush()
		logfile.close()
	alertfile.close()
	#write flag
	alertfile=open(alertfilename,'w')
	alertfile.write("1")
	alertfile.flush()
	alertfile.close()
	
#发送恢复事件,写日志,重置标志文件为正常状态
def lc_sendrecovery(alertfilename,strs,logfile):
	#init
	alertfile=open(alertfilename,'a')
	alertfile.write("")
	alertfile.flush()
	alertfile.close()
	#read flag
	alertfile=open(alertfilename,'r')
	flag=alertfile.read()
	if "1" in flag:
		lc_alert(strs)
		logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		logfile.write(logdate+" "+strs+"\n")
		logfile.flush()
		logfile.close()
	alertfile.close()
	#write flag
	alertfile=open(alertfilename,'w')
	alertfile.write("0")
	alertfile.flush()
	alertfile.close()

#加密与解密
lc_cryptkey = 62
def lc_encrypt(s):
	try:
		s=s.decode('gbk')
	except:
		pass
	try:
		s=s.encode('utf8')
	except:
		pass
	b = bytearray(s)
	n = len(b)
	c = bytearray(n*2)
	j = 0
	for i in range(0, n):
		b1 = b[i]
		b2 = b1 ^ lc_cryptkey
		c1 = b2 % 16
		c2 = b2 // 16
		c1 = c1 + 65
		c2 = c2 + 65
		c[j] = c1
		c[j+1] = c2
		j = j+2
	return c
def lc_decrypt(s):
	try:
		s=s.decode('gbk')
	except:
		pass
	try:
		s=s.encode('utf8')
	except:
		pass
	c = bytearray(s)
	n = len(c)
	if n % 2 != 0:
		raise TypeError("DecryptFailed")
	n = n // 2
	b = bytearray(n)
	j = 0
	for i in range(0, n):
		c1 = c[j]
		c2 = c[j+1]
		j = j+2
		c1 = c1 - 65
		c2 = c2 - 65
		b2 = c2*16 + c1
		b1 = b2^ lc_cryptkey
		b[i]= b1
	try:
		b=b.encode('utf8')
	except:
		pass
	return b


#定义操作sqlite类
#class lc_dboperater:
#	def __init__(self,dbfile,tablename,tablefield):
#		self.dbfile=dbfile
#		self.tablename=tablename
#		self.tablefield=tablefield
#		self.conn=sqlite3.connect(self.dbfile)
#		self.conn.text_factory = bytes
#		self.cur=self.conn.cursor()
#	def create_db(self):
#		createsql="create table if not exists "+self.tablename+"("+self.tablefield+")"
#		self.conn.execute(createsql)
#		return
#	def execute_sql(self,sql):
#		self.conn.execute(sql)
#		self.conn.commit()
#		return
#	def select_sql(self,sql):
#		self.cur.execute(sql)
#		self.res=self.cur.fetchall()
#		return self.res
#	def close_db(self):
#		self.cur.close()
#		self.conn.close()
#	def update_eventsdb(self,agent_hostname,Node,AlertGroup,AlertKey,Severity,Type,Summary,logfile):
#		LastOccurrence=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
#		selectsql="select Type from lc_events where Node='"+Node+"' and AlertGroup='"+AlertGroup+"' and AlertKey='"+AlertKey+"'"
#		deletesql="delete from lc_events where Node='"+Node+"' and AlertGroup='"+AlertGroup+"' and AlertKey='"+AlertKey+"'"
#		updatesql="update lc_events set LastOccurrence='"+LastOccurrence+"' where Node='"+Node+"' and AlertGroup='"+AlertGroup+"' and AlertKey='"+AlertKey+"'"
#		insertsql="insert into lc_events(Node,AlertGroup,AlertKey,Severity,Type,LastOccurrence,Summary) values ('"+Node+"','"+AlertGroup+"','"+AlertKey+"','"+Severity+"','"+Type+"','"+LastOccurrence+"','"+Summary+"')"
#		res=self.select_sql(selectsql)
#		strs=lc_gen_alert(agent_hostname,Node,AlertGroup,AlertKey,Severity,Type,Summary)
#		if len(res)==0:
#			self.execute_sql(insertsql)
#			if int(Type)==1:
#				lc_alert(strs)
#				logfile.write(LastOccurrence+" "+strs+"\n")
#				logfile.flush()
#		elif res[0][0]==Type:
#			self.execute_sql(updatesql)
#		else:
#			self.execute_sql(deletesql)
#			self.execute_sql(insertsql)
#			lc_alert(strs)
#			logfile.write(LastOccurrence+" "+strs+"\n")
#			logfile.flush()
#	def update_eventsdb_rt(self,agent_hostname,Node,AlertGroup,AlertKey,Severity,Type,Summary,logfile):
#		LastOccurrence=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
#		selectsql="select Type from lc_events where Node='"+Node+"' and AlertGroup='"+AlertGroup+"' and AlertKey='"+AlertKey+"'"
#		deletesql="delete from lc_events where Node='"+Node+"' and AlertGroup='"+AlertGroup+"' and AlertKey='"+AlertKey+"'"
#		updatesql="update lc_events set LastOccurrence='"+LastOccurrence+"' where Node='"+Node+"' and AlertGroup='"+AlertGroup+"' and AlertKey='"+AlertKey+"'"
#		insertsql="insert into lc_events(Node,AlertGroup,AlertKey,Severity,Type,LastOccurrence,Summary) values ('"+Node+"','"+AlertGroup+"','"+AlertKey+"','"+Severity+"','"+Type+"','"+LastOccurrence+"','"+Summary+"')"
#		res=self.select_sql(selectsql)
#		strs=lc_gen_alert(agent_hostname,Node,AlertGroup,AlertKey,Severity,Type,Summary)
#		if len(res)==0:
#			self.execute_sql(insertsql)
#			if int(Type)==1:
#				lc_alert(strs)
#				logfile.write(LastOccurrence+" "+strs+"\n")
#				logfile.flush()
#		else:
#			self.execute_sql(deletesql)
#			self.execute_sql(insertsql)
#			lc_alert(strs)
#			logfile.write(LastOccurrence+" "+strs+"\n")
#			logfile.flush()
#	def update_alert_status(self,Manager,Node,AlertGroup,AlertKey,Severity,Type,Summary,logfile):
#		#Identifier = Node + " " + AlertGroup + " " + AlertKey + " " + Severity + " " + Type
#		LastOccurrence = str(int(time.time()))
#		now=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
#		strs=lc_gen_alert(Manager,Node,AlertGroup,AlertKey,Severity,Type,Summary)
#		#print strs
#		logfile.write(now+" "+strs+"\n")
#		logfile.flush()
#		Tally="1"
#		#print "str:"+Manager
#		#print "str:"+Node
#		#print "str:"+AlertGroup
#		#print "str:"+AlertKey
#		#print "str:"+Severity
#		#print "str:"+Severity
#		#print "str:"+Type
#		#print "str:"+LastOccurrence
#		#print "str:"+LastOccurrence
#		#print "str:"+Summary
#		selectsql="select Tally from lc_status where Node='"+Node+"' and AlertGroup='"+AlertGroup+"' and AlertKey='"+AlertKey+"' and Manager='"+Manager+"'"
#		#print selectsql
#		#deletesql="delete from lc_status where Node='"+Node+"' and AlertGroup='"+AlertGroup+"' and AlertKey='"+AlertKey+"' and Manager='"+Manager+"'"
#		#updatesql="update lc_status set LastOccurrence='"+LastOccurrence+"',Severity='"+Severity+"',Summary='"+Summary+"',Tally='"+Tally+"' where Node='"+Node+"' and AlertGroup='"+AlertGroup+"' and AlertKey='"+AlertKey+"' and Manager='"+Manager+"'"
#		#print updatesql
#		insertsql="insert into lc_status(Manager,Node,AlertGroup,AlertKey,Severity,OSeverity,Type,FirstOccurrence,LastOccurrence,Summary,Tally) values ('"+Manager+"','"+Node+"','"+AlertGroup+"','"+AlertKey+"','"+Severity+"','"+Severity+"','"+Type+"','"+LastOccurrence+"','"+LastOccurrence+"','"+Summary+"','"+Tally+"')"
#		#print insertsql
#		res=self.select_sql(selectsql)
#		#print res
#		if len(res)==0 or res[0][0]==None:
#			#print "insert"
#			self.execute_sql(insertsql)
#			#time.sleep(100)
#		else:
#			#print "update"
#			#print res[0][0]
#			Tally=str(int(res[0][0])+1)
#			updatesql="update lc_status set LastOccurrence='"+LastOccurrence+"',Severity='"+Severity+"',Summary='"+Summary+"',Tally='"+Tally+"' where Node='"+Node+"' and AlertGroup='"+AlertGroup+"' and AlertKey='"+AlertKey+"' and Manager='"+Manager+"'"
#			#print updatesql
#			self.execute_sql(updatesql)
#			#time.sleep(100)
#	def update_alert_history(self,Manager,Node,AlertGroup,AlertKey,Severity,Type,Summary,logfile):
#		#Identifier = Node + " " + AlertGroup + " " + AlertKey + " " + Severity + " " + Type
#		LastOccurrence = str(int(time.time()))
#		#now=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
#		#logfile.write(now+" "+strs+"\n")
#		#logfile.flush()
#		#Tally='1'
#		#selectsql="select Tally from lc_status where Node='"+Node+"' and AlertGroup='"+AlertGroup+"' and AlertKey='"+AlertKey+"' and Manager='"+Manager+"'"
#		#deletesql="delete from lc_status where Node='"+Node+"' and AlertGroup='"+AlertGroup+"' and AlertKey='"+AlertKey+"' and Manager='"+Manager+"'"
#		#updatesql="update lc_status set LastOccurrence='"+LastOccurrence+"',Severity='"+Severity+"',Summary='"+Summary+"',Tally='"+Tally+"' where Node='"+Node+"' and AlertGroup='"+AlertGroup+"' and AlertKey='"+AlertKey+"' and Manager='"+Manager+"'"
#		#insertsql="insert into lc_status(Manager,Node,AlertGroup,AlertKey,Severity,OSeverity,Type,FirstOccurrence,LastOccurrence,Summary) values ('"+Manager+"','"+Node+"','"+AlertGroup+"','"+AlertKey+"','"+Severity+"','"+OSeverity+"','"+Type+"','"+LastOccurrence+"','"+LastOccurrence+"','"+Summary+"')"
#		insertsql="insert into lc_history(Manager,Node,AlertGroup,AlertKey,Severity,Type,LastOccurrence,Summary) values ('"+Manager+"','"+Node+"','"+AlertGroup+"','"+AlertKey+"','"+Severity+"','"+Type+"','"+LastOccurrence+"','"+Summary+"')"
#		self.execute_sql(insertsql)
#		#res=self.select_sql(selectsql)
#		#if len(res)==0:
#		#	self.execute_sql(insertsql)
#		#else:
#		#	Tally=str(int(res[0][0])+1)
#		#	self.execute_sql(updatesql)
#			
#			
#	def insert_historydb(self,Node,Name,Value):
#		#NTime=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
#		NTime=int(time.time())
#		insertsql="insert into "+self.tablename+"(Node,Name,Value,NTime) values ('"+Node+"','"+Name+"','"+Value+"','"+str(NTime)+"')"
#		res=self.execute_sql(insertsql)

#定义操作mongodb类
class lc_mongodb_operater:

	def __init__(self,host,port):
		self.conn=None
		self.mhost=host
		self.mport=port

	def connect(self):
		self.conn = pymongo.Connection(host=self.mhost,port=self.mport)

	def close(self):
		return self.conn.disconnect()

	def getConn(self):
		return self.conn

	def getServerInfo(self):
		serverinfo = self.conn.server_info()
		return serverinfo

	def listDatabase(self):
		databases = self.conn.database_names()

	def listCollection(self):
		databases = self.conn.collection_names()
		return databases

	def useDatabase(self,dbname):
		#连接库
		oper = self.conn[dbname]
		return oper

	def UseCollection(self,opername,tablename):
		#连接表
		oper = opername[tablename]
		return oper

	def createTable(self,dbname,tablename):
		#创建库和表
		oper = self.conn.dbname.tablename
		return oper

	def dropDB(self,dbname):
		#删除库
		oper=self.conn.drop_database(dbname)
		return oper

	def dropCollection(self,collection_name):
		#删除表
		oper=self.conn.drop_collection(collection_name)
		return oper

	def insertDatas(self,opername,datas):
		opername.insert(datas)

	def deleteData(self,opername,exprs):
		opername.remove(exprs)

	def updateData(self,opername,exprs,datas):
		opername.update(exprs,{'$set':datas},upsert=False,multi=True)

	def queryData(self,opername,exprcont,sortcont,topn):
		#查询数据
		rows = opername.find(exprcont).sort(sortcont).limit(topn)
		return rows
		#self.printResult(rows)
		#查询一个数据
		#print lifeba_users.find_one()
		#带条件查询
		#printResult(lifeba_users.find({'name':'steven2'}))
		#printResult(lifeba_users.find({'name':{'$gt':25}}))

	def queryData_nosort(self,opername,exprcont,topn):
		#查询全部数据
		rows = opername.find(exprcont).limit(topn)
		return rows

	def queryData_count(self,opername,exprcont):
		#查询全部数据数量
		rows = opername.find(exprcont).count()
		return rows

	def genResult(self,rows):
		res=[]
		i=0
		for row in rows:
			tres={}
			for key in row.keys():#遍历字典
				tres[key]=row[key]
				#print key
				#print row[key]
			res.insert(i,tres)
			i+=1
		return res

	def insert_historydb(self,Node,Name,Value):
		NTime=int(time.time())
		datas=[{"Node":Node,"Name":Name,"Value":Value,"Time":NTime}]
		res=self.execute_sql(insertsql)

	def update_eventsdb(self,oper,agent_hostname,Node,AlertGroup,AlertKey,Severity,Type,Summary):
		LastOccurrence=int(time.time())
		strs=lc_gen_alert(agent_hostname,Node,AlertGroup,AlertKey,Severity,Type,Summary)
		expr={'Node':Node,'AlertGroup':AlertGroup,'AlertKey':AlertKey}
		sortcont=[("Node",pymongo.ASCENDING),("AlertGroup",pymongo.ASCENDING),("AlertKey",pymongo.ASCENDING)]
		Summary=Summary
		AlertGroup=AlertGroup
		AlertKey=AlertKey
		datas={'Node':Node,'AlertGroup':AlertGroup,'AlertKey':AlertKey,'Severity':Severity,'Type':Type,'Summary':Summary,'LastOccurrence':LastOccurrence}
		opts=self.queryData(oper,expr,sortcont,0)
		res=self.genResult(opts)

		if len(res)==0:
			self.insertDatas(oper,datas)
			if int(Type)==1:
				lc_alert(strs)
		elif int(res[0]['Type'])==int(Type):
			self.updateData(oper,expr,datas)
			#self.deleteData(oper,expr)
			#self.insertDatas(oper,datas)
		else:
			self.updateData(oper,expr,datas)
			#self.deleteData(oper,expr)
			#self.insertDatas(oper,datas)
			lc_alert(strs)
		
	def update_eventsdb_rt(self,oper,agent_hostname,Node,AlertGroup,AlertKey,Severity,Type,Summary):
		LastOccurrence=int(time.time())
		strs=lc_gen_alert(agent_hostname,Node,AlertGroup,AlertKey,Severity,Type,Summary)
		expr={'Node':Node,'AlertGroup':AlertGroup,'AlertKey':AlertKey}
		sortcont=[("Node",pymongo.ASCENDING),("AlertGroup",pymongo.ASCENDING),("AlertKey",pymongo.ASCENDING)]
		Summary=Summary
		AlertGroup=AlertGroup
		AlertKey=AlertKey
		datas={'Node':Node,'AlertGroup':AlertGroup,'AlertKey':AlertKey,'Severity':Severity,'Type':Type,'Summary':Summary,'LastOccurrence':LastOccurrence}
		opts=self.queryData(oper,expr,sortcont,0)
		res=self.genResult(opts)
		
		if len(res)==0:
			self.insertDatas(oper,datas)
		else:
			self.updateData(oper,expr,datas)
			
		lc_alert(strs)

	def update_alert_status(self,oper,TableFields,logfile):
		print TableFields
		LastOccurrence = str(int(time.time()))
		now=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		#strs=lc_gen_alert(TableFields['Manager'],TableFields['Node'],TableFields['AlertGroup'],TableFields['AlertKey'],TableFields['Severity'],TableFields['Type'],TableFields['Summary'])
		#print strs
		#logfile.write(now+" "+strs+"\n")
		#logfile.flush()
		TableFields['Tally']=1
		TableFields['LastOccurrence']=LastOccurrence

		#expr={'Node':TableFields['Node'],'AlertGroup':TableFields['AlertGroup'],'AlertKey':TableFields['AlertKey']}
		expr={'Identifier':TableFields['Identifier']}
		sortcont=[("Node",pymongo.ASCENDING),("AlertGroup",pymongo.ASCENDING),("AlertKey",pymongo.ASCENDING)]
		#Summary=Summary
		#AlertGroup=AlertGroup
		#AlertKey=AlertKey
		OwnerUID=""
		#datas={
		#	'Manager':Manager,
		#	'Node':Node,
		#	'AlertGroup':AlertGroup,
		#	'AlertKey':AlertKey,
		#	'Severity':int(Severity),
		#	'Type':int(Type),
		#	'Summary':Summary,
		#	'OwnerUID':OwnerUID,
		#	'LastOccurrence':LastOccurrence,
		#	'FirstOccurrence':LastOccurrence,
		#	'Tally':int(Tally)
		#	}
		opts=self.queryData(oper,expr,sortcont,0)
		res=self.genResult(opts)

		if len(res)==0:
			TableFields['FirstOccurrence']=LastOccurrence
			self.insertDatas(oper,TableFields)
		else:
			#print res
			Tally=int(res[0]['Tally'])+1
			#print Tally
			#self.deleteData(oper,expr)
			datas={
				'Severity':TableFields['Severity'],
				'Type':TableFields['Type'],
				'Summary':TableFields['Summary'],
				'LastOccurrence':LastOccurrence,
				'LastModified':LastOccurrence,
				'Tally':Tally
				}
			self.updateData(oper,expr,datas)
			#lc_alert(strs)
			
	def update_alert_history(self,oper,TableFields,logfile):
		LastOccurrence = str(int(time.time()))
		now=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		#strs=lc_gen_alert(Manager,Node,AlertGroup,AlertKey,Severity,Type,Summary)
		#print strs
		#logfile.write(now+" "+strs+"\n")
		#logfile.flush()
		#Tally='1'
		expr={'Node':TableFields['Node'],'AlertGroup':TableFields['AlertGroup'],'AlertKey':TableFields['AlertKey']}
		#sortcont=[("Node",pymongo.ASCENDING),("AlertGroup",pymongo.ASCENDING),("AlertKey",pymongo.ASCENDING)]
		#Summary=Summary
		#AlertGroup=AlertGroup
		#AlertKey=AlertKey
		#datas={
		#	'Manager':Manager,
		#	'Node':Node,
		#	'AlertGroup':AlertGroup,
		#	'AlertKey':AlertKey,
		#	'Severity':int(Severity),
		#	'Type':int(Type),
		#	'Summary':Summary,
		#	'LastOccurrence':LastOccurrence
		#	}
		#opts=self.queryData(oper,expr,sortcont,0)
		#res=self.genResult(opts)
		self.insertDatas(oper,TableFields)

#定义操作Oracle类
class lc_oracledb_operater:
	
	def __init__(self,sqlcmd,host,port,sid,username,password):
		#print sqlcmd,username,password,host,port,sid
		self.cmd="%s %s/%s@%s:%s/%s" % (sqlcmd,username,password,host,port,sid)
	
	def executesql(self,sqlstr):
		popen=subprocess.Popen(self.cmd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,shell=True)
		time.sleep(0.1)
		popen.stdin.write("\n"+sqlstr+";\n")
		time.sleep(0.1)
		popen.stdin.write("exit;\n")
		time.sleep(0.1)
		return popen.stdout.read()


#返回ASCII值
def lc_genacsii(input):
	res=str(input)
	lchome=lc_getlchome()
	file=open(lchome+'/conf/lc_ascii.conf','r')
	for line in file.readlines():
		lines=line.split('\t')
		if str(input)==str(lines[0]):
			res=lines[2]
	file.close()
	return res